/**
 * WidgetEvent module
 */

//import eventHelper from "../../../utils/EventHelper";
import React, {Component} from 'react';

import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import editorActions from '../../../actions/Editor/editor';
import tool from "../../../utils/tool";
import consts from "../../../consts/consts";
import widgetTypes from "../../../consts/widgetTypes";
import WidgetEventForm from "./WidgetEventForm";
//var dataProvider from "../provider/dataProvider";
import WidgetEventExtend from "./WidgetEventExtend";
//var BasePermission from "../model/BasePermission";
import WidgetEventUrlInput from "./WidgetEventUrlInput";
import WidgetEventPhoneInput from "./WidgetEventPhoneInput";
import WidgetEventVideoInput from "./WidgetEventVideoInput";
import WidgetEventPagingInput from "./WidgetEventPagingInput";
import WidgetEventSearchNearby from "./WidgetEventSearchNearby";
import WidgetEventLocationInput from "./WidgetEventLocationInput";
import WidgetEventDownloadInput from "./WidgetEventDownloadInput";
import WidgetEventShare from "./WidgetEventShare";
import WidgetEventTrigger from "./WidgetEventTrigger";
class WidgetEvent extends Component{
    constructor(props) {
        super(props);
        this.state = {
            showSelect: false,
            showToggle: false
        };
    }
    getInitialProps(){
        return {
            root: {},
            widget: {},
            timelines: {}
        }
    }
    componentWillMount(){
        this.initTranslate();
        var widget = this.props.widget;

        var is_threed = consts.WIDGET_TYPE.THREED === widget.type;
        var loop_events = is_threed ? consts.THREED_EVENTS : consts.WIDGET_EVENTS;

        this.form = {};
        this.select = true;
        this.timelines = [];
        this.ThreedList = [];
        this.widgetEvents = [];
        this.typeName = this.NoEvent;
        this.btnName = $._('Change interactive events');
        this.no_action = consts.WIDGET_NO_EVENT.indexOf(widget.type) != -1;
        this.disabled = consts.WIDGET_TYPE_NO_EDITABLE_TYPES.indexOf(widget.type) != -1;

        this.CONST = {
            MATERIAL_TYPE: {
                BASE: "base",
                LOOP: "loop"
            },
            LOOP_LIMIT: 10,
            CN_COUNT_MAPPING: {
                0: $._("One"),
                1: $._("Two"),
                2: $._("Threed"),
                3: $._("Four"),
                4: $._("Five"),
                5: $._("Six"),
                6: $._("Seven"),
                7: $._("Eight"),
                8: $._("Nine"),
                9: $._("Ten")
            }
        };

        this.permissionFactory = {};
        this.widgetEvents = loop_events; //权限问题待处理

        if (widget.action){
            this.form.model = widget.action;
            this.getTypeName();

            if (this.no_action || this.disabled){
                this.select = false;
            }

            if (widget.action.type == -1){
                this.btnName = $._('Add interactive events');
            }
        }
        //视频,音乐,相册,模型不支持添加交互
        if (this.no_action) this.btnName = $._('can not support events');
        this.initThreedList();
    }
    initThreedList(){
        const {widgets} = this.props;
        widgets.forEach(function (widget){
            var data = $.extend(true, {}, widget);
            if (data.type == consts.WIDGET_TYPE.THREED){
                // 有播放动作或者贴图的才可选
                this.ThreedList.push(data);
            }
        }.bind(this));
    }
    handleOnShowExtendDialog(){
        var root = this.props.root;
        root.setState({
            status: {
                displayDialog: "extend"
            }
        });
    }
    handleOnToggleShowSelect(){
        this.setState({
            showSelect: !this.state.showSelect
        });
    }
    handleOnSelectWidgetEvent(type, e){
        this.handleOnToggleShowSelect();
        var curActionType = this.form.model.type;
        //分享组件type都为24,需要单独处理

        if (curActionType == type && type != "-1" && type != consts.WIDGET_TYPE.SHARE) return;

        var widget = this.props.widget, root = this.props.root;
        widget.action = this.form.model = { type: type };

        // 提交表单内容事件初始化为预约报名
        if (type == consts.WIDGET_TYPE.FORM){
            widget.action = this.form.model = {
                type: type,
                form_type: 0,
                title: consts.FORMTYPE[0].value,
            }
            widget.tip_text = consts.FORMTYPE[0].value;
            // 初始化表单内容
            widget = tool.reBuildFormContent(widget);
        } else if(type == consts.WIDGET_TYPE.SHARE){
            //分享组件type都为24,需要单独处理
            widget.action = this.form.model = {
                type: consts.WIDGET_TYPE.SHARE,
                share_way: e,
                share_type: 0,
                h5_ar_url_switch: 0,
                link_picture_share_url: this.props.root.state.page.page_background.url,
                picture_share_url:this.props.root.state.page.page_background.url,
                title: consts.SHARE_BTNS[e].value,
            }
            widget.tip_text = consts.SHARE_BTNS[e].value;
        }
        this.updateWidget(widget);
//        eventHelper.trigger(consts.EVENTS.THREED_WIDGET_PROPERTY_CHANGED, widget);
    }
    updateWidget(widget){
        const {updateWidget,setState} = this.props;
        setState({selectedWidget: widget});
        updateWidget(widget);
    }
    updateTimeline(timeline){
        var timelines = this.timelines;
        var result = [];

        timelines.forEach(function (_timeline){
            if (_timeline.widget_id == timeline.widget_id){
                result.push(timeline);
            } else {
                result.push(_timeline);
            }
        });

        this.timelines = result;
    }
    getTypeName(){
        const {widget} = this.props;
        this.typeName = this.NoEvent;
        if (this.no_action){
            this.typeName = consts.WIDGET_NO_EVENT_DISPLAY.filter(function (ele, pos){
                return ele.value == widget.type;
            })[0].name;
        } else {
            let type = this.form.model.type === -1 ? widget.type : this.form.model.type;
            let _actions = consts.WIDGET_EVENTS.filter(function (ele, pos){
                return ele.value == type;
            }.bind(this));

            this.form.model.type = widget.action.type = type;
            let isAppDownload = (this.form.model.type != widgetTypes.APP_DOWNLOAD);
            if (_actions.length == 0 && isAppDownload) widget.action.type = -1;
            if (widget.action.type != -1) this.typeName = _actions[0].name;
            if(widget.action.type == widgetTypes.SHARE){
                let share_way = widget.action.share_way;
                let _action = consts.SHARE_EVENTS.filter(function(ele, pos){
                    return ele.share_way == share_way;
                }.bind(this));
                this.typeName = _action[0].name
            }
        }
    }
    handleOnSelectThreed(type, param, materialType, index, e){
        const {widget} = this.props;
        let params,select_material;
        let element = $(e.target), val = element.val();

        if ("widget_id" === type){
            params = {
                widget_id: val
            };
        } else if("select_material" == type) {
            // base
            if (materialType === this.CONST.MATERIAL_TYPE.BASE){
                select_material = widget.action.select_material ? widget.action.select_material : {};
                select_material[param] = val;
                params = {
                    select_material: select_material
                };
            // extra
            } else if(materialType === this.CONST.MATERIAL_TYPE.EXTRA) {
                let select_materials = widget.action.select_materials;
                select_materials[index][param] = val;
                params = {
                    select_materials: select_materials
                };
            }
        } else if("select_animation" === type) {
            let animations = widget.action.select_animations || [];
            let index = animations.indexOf(param);
            param = parseInt(param);
            if (index == -1){
                animations.push(param);
            } else {
                animations.splice(index, 1);
            }
            params = {
                select_animations: animations,
                select_animation: parseInt(animations[0])
            };
        } else if("looptype" === type) {
            let looptype = !widget.action.looptype ? 1 : 0;
            params = {
                looptype: looptype
            };
        }

        $.extend(widget.action, params);

        if (!widget.action.widget_id){
            delete widget.action.select_material;
            delete widget.action.select_materials;
            delete widget.action.select_animation;
            delete widget.action.select_animations;
        }
        if(!widget.action.select_animations){
            delete widget.action.select_animation;
        } else if(!widget.action.select_animations.length){
            delete widget.action.select_animation;
        }

        this.updateWidget(widget);
    }
    handleOnAddLoopMaterial(materials){
        const {widget} = this.props,{action} = widget,{select_materials} = action || [];
        let material = {};
        materials.forEach(function (item){
            material[item[0]] = "";
        });
        select_materials.push(material);
        widget.action.select_materials = select_materials;

        this.updateWidget(widget);
    }
    handleOnRemoveLoopMaterial(index){
        const {widget} = this.props,{action} = widget,{select_materials} = action || [];
        if (select_materials.length){
            select_materials.splice(index, 1);
            widget.action.select_materials = select_materials;
            this.updateWidget(widget);
        }
    }
    materialNodesCreator(materials, select_material, type, index){
        let titleNode = "";
        if (type === this.CONST.MATERIAL_TYPE.EXTRA){
            titleNode =
                <div className="loop_material_header">
                    <span>{$._('Loop switch')}{this.CONST.CN_COUNT_MAPPING[index]}</span>
                    <a href="javascript:;" onClick={() => this.handleOnRemoveLoopMaterial(index)}>{$._("Delete")}</a>
                </div>
        }

        return (
            <div key={index} className="threed_Texture_default">
            {titleNode}
            {
                materials.map(function (u3d_material){
                    return (
                        <div key={u3d_material[0]} className="Texture_default_list">
                            <img src="/static/idealsee/images/new_editor/editor/Bitmap.png" width="20" />
                            <span>{u3d_material[0]}</span>
                            <select className="select_materials" data-value={u3d_material[0]} name="select_material" onChange={(e) => this.handleOnSelectThreed("select_material", u3d_material[0], type, index, e)} className="select-threed" value={ select_material ? select_material[u3d_material[0]] : "-1" }>
                                <option value="-1" key="please_choose">{$._('Please choose')}</option>
                                {
                                    u3d_material[1].map(function (u3d_name, index){
                                        return (
                                            <option key={index} value={u3d_name}>
                                                {u3d_name}
                                            </option>
                                        )
                                    })
                                }
                            </select>
                        </div>
                    )
                }.bind(this))
            }
            </div>
        )
    }
    initTranslate(){
        this.NoEvent = $._('No event');
    }
    handleOnChangeTab(e){
        const {setState,status} = this.props;
        var tabName = $(e.target || e.srcElement).attr("data-type");
        if(tabName){
            status.showFloatingHead = true;
            let param = {
                focusTab: tabName,
                status: status
            }
            setState(param)
        }
    }
    render(){
        const {widget,timelines,pages,fromTemplate,status,updateWidget,setState,selectedPageId} = this.props;
        const {showFloatingHead} = status;
        let form = this.form,
            url = widget.action.url || "";

        let formModelTypeNode = "", formModelTypeInnerNode = "";

        // 解决切换不同组件时，交互事件未对应更新问题
        if (widget.action){
            form.model = widget.action;
        }

        let showChangeEventButton = consts.WIDGET_CAN_CHANGE_EVENT_TYPE.indexOf(widget.type)> -1;
        form.model.select_materials = form.model.select_materials || [];
        form.model.select_animations = form.model.select_animations || [];

        // 获取当前选中模型
        let chooseThreed = null;
        this.ThreedList.forEach(function (threed){
            if (form.model.widget_id == threed.id){
                chooseThreed = threed;
            }
        });

        // 当前选中模型的数据
        let u3d_materials = (chooseThreed && chooseThreed.u3d_materials) ? chooseThreed.u3d_materials : [];
        let u3d_animations = (chooseThreed && chooseThreed.u3d_animations) ? chooseThreed.u3d_animations : [];

        // 当前组件选中贴图数据
        let select_materials = form.model.select_materials;

        switch (parseInt(form.model.type)){
            case 0:
                formModelTypeNode = <WidgetEventPhoneInput widget={widget} form={form} updateWidget={updateWidget} setState={setState}/>
                break;
            case 1:
                formModelTypeNode = <WidgetEventUrlInput />
                break;
            case 2:
                formModelTypeNode = <WidgetEventLocationInput />
                break;
            case 3:
                formModelTypeNode = <WidgetEventExtend />
                break;
            case 11:
                formModelTypeNode = <WidgetEventTrigger />
                break;
            case 14:
                formModelTypeNode = <WidgetEventVideoInput widget={widget} />
                break;
            case 15:
                formModelTypeNode = <WidgetEventPagingInput />
                break;
            case 17:
                var hasThreedNode = "";
                var MaterialsNode = "";

                if (this.ThreedList.length){
                    hasThreedNode =
                        <select name="widget_id" onChange={(e) => this.handleOnSelectThreed("widget_id",'','','',e)} className="select-threed" value={form.model.widget_id || ""}>
                            <option value="" key="please_choose">{$._('Please choose')}</option>
                            {
                                this.ThreedList.map(function (threed){
                                    var fbx_name = threed.u3d_fbx_name || threed.html;
                                    return (
                                        <option value={threed.id} key={threed.id}>
                                            {fbx_name}
                                        </option>
                                    )
                                }.bind(this))
                            }
                        </select>

                    // 添加循环切换按钮
                    var addLoopMaterialNode = "";
                    // 循环切换贴图节点
                    var loopMaterialsNode = "";
                    if (u3d_materials.length){
                        MaterialsNode = this.materialNodesCreator(u3d_materials, form.model.select_material, this.CONST.MATERIAL_TYPE.BASE, 0);

                        // 限制循环切换个数
                        if (select_materials.length < this.CONST.LOOP_LIMIT){
                            addLoopMaterialNode =
                                <div className="add_loop_region">
                                    <div className="add_loop_btn" onClick={() => this.handleOnAddLoopMaterial(u3d_materials)}>
                                        <i></i>
                                        <span>{$._("Add loop switch")}</span>
                                    </div>
                                    <div className="add_loop_tip">
                                        {$._('Add after continuous click on the loop switch map')}
                                    </div>
                                </div>
                        }

                        loopMaterialsNode =
                            select_materials.map(function (material, index){
                                return (
                                    this.materialNodesCreator(u3d_materials, material, this.CONST.MATERIAL_TYPE.EXTRA, index)
                                )
                            }.bind(this))
                    } else if(!u3d_materials.length && form.model.widget_id){
                        MaterialsNode =
                            <div className="threed_Texture_default">
                                <div className="no_default_sd">{$._('No textures in the model')}</div>
                            </div>
                    }
                }
                formModelTypeNode =
                    <div form={form}>
                        <div className="form-group about_threed threed_Texture">
                            <a className="threed_help" href="/web/resource/help?select=4" target="_blank">{$._('How to make a model to support the change map')}</a>
                            <div className="threed_3d">
                                <div className="select_3d">
                                    <label>{$._("Model choose")}</label>
                                    <select defaultValue="-1" style={{ display: this.ThreedList.length ? "none" : "block" }}>
                                        <option value="-1">{$._("no model in this page")}</option>
                                    </select>
                                    {hasThreedNode}
                                </div>
                                {MaterialsNode}
                                {addLoopMaterialNode}
                                {loopMaterialsNode}
                            </div>
                        </div>
                    </div>
                break;
                case 18:
                    var hasThreedNode = "";
                    var animationsNode = "";
                    if (this.ThreedList.length){
                        hasThreedNode =
                            <select name="widget_id" onChange={(e) => this.handleOnSelectThreed("widget_id","","","",e)} className="select-threed" value={form.model.widget_id || ""}>
                                <option value="" key="please_choose">{$._('Please choose')}</option>
                                {
                                    this.ThreedList.map(function (threed){
                                        var fbx_name = threed.u3d_fbx_name || threed.html;
                                        return (
                                            <option value={threed.id} key={threed.id}>
                                                {fbx_name}
                                            </option>
                                        )
                                    }.bind(this))
                                }
                            </select>

                          if (u3d_animations.length){
                              animationsNode =
                                  <div className="threed_animation_default">
                                      {
                                          u3d_animations.map(function (u3d_animation, pos){
                                              return (
                                                  <div key={u3d_animation[0]} className="animation_default_list select-threed" name="select_animation" onClick={(e) => this.handleOnSelectThreed("select_animation", pos,"","",e)} data-value={this.pos}>
                                                      <div className={"info-item-icon " + ((form.model.select_animations.indexOf(pos) == -1) ? "icon-uniF471" : "icon-unxe71f")}></div>
                                                      <span className="animation_default_name">{u3d_animation[0]}</span>
                                                      <span className="pull-right">
                                                          <span>{u3d_animation[1][0]}</span>
                                                          <span>-</span>
                                                          <span>{u3d_animation[1][1]}</span>
                                                          <span>f</span>
                                                      </span>
                                                  </div>
                                              )
                                          }.bind(this))
                                      }
                                  </div>
                          } else if(!u3d_animations.length && form.model.widget_id){
                              animationsNode =
                                  <div className="threed_animation_default">
                                      <div className="no_default_sd">{$._("No action in model")}</div>
                                  </div>
                          }
                      }
                      formModelTypeNode =
                          <div form={form}>
                              <div className="form-group about_threed threed_Texture">
                                  <a className="threed_help" href="/web/resource/help?select=4" target="_blank">{$._('How to make a model to support the action')}</a>
                                  <div className="threed_3d">
                                      <div className="select_3d">
                                          <label>{$._("Model choose")}</label>
                                          <select defaultValue="-1" style={{display: this.ThreedList.length ? "none" : "block"}}>
                                              <option value="-1">{$._("no model in this page")}</option>
                                          </select>
                                          {hasThreedNode}
                                      </div>
                                      <div className="info-item">
                                          <label className="label-repeat info-item-label">{$._("Loop playBack single action")}</label>
                                          <div className={"select-threed info-item-icon " + (form.model.looptype ? "icon-uniF52F" : "icon-uniF471")} onClick={(e) => this.handleOnSelectThreed("looptype","","","",e)} name="looptype"></div>
                                      </div>
                                      <div className="tip">
                                          {$._("multiple click will in order to switch multiple action")}
                                      </div>
                                      {animationsNode}
                                  </div>
                              </div>
                          </div>
                      break;
                case 22:
                    formModelTypeNode = <WidgetEventForm />
                    break;
                case 21:
                    formModelTypeNode = <WidgetEventSearchNearby />
                    break;
               case 24:
                  formModelTypeNode = <WidgetEventShare />
                  break;
        }

        var widgetTypeNode = "";
        switch (parseInt(widget.type)){
            case 7:
                widgetTypeNode = <div></div>
                break;
            case 8:
                widgetTypeNode = <WidgetEventDownloadInput />
                break;
        }
        var headerNode = "";
        if (showFloatingHead){
            var parent= this.props.parent;
            headerNode =
                <header className="floatingbtn_head">
                    <div onClick={(e) => this.handleOnChangeTab(e)} data-type={consts.FOCUS_TABS.FIXEDBTN}>{$._('Fixed button property')}</div>
                    <div className="floatingfocus">{$._('Interactive')}</div>
                </header>
        }
        this.getTypeName();
        return (
            <div className="widget-event-container" data-widget-event data-visible="visible" data-widget-events="widgetEvents">
                <form noValidate className="property" name="form.name">
                    {headerNode}
                    <div className="line btn-holder" style={{display:showChangeEventButton ? "none": "block"}}>
                        <button type="button" disabled={this.no_action} onClick={() => this.handleOnToggleShowSelect() } className={"btn-eidt-widget-event " + (this.no_action ? "disabled" : "")} >
                            <span className="button-item">{this.btnName}</span>
                        </button>
                    </div>
                    <div className="select-widget-event" style={{display: this.state.showSelect ? "block" : "none"}}>
                        <div className="select-evtype">
                            <div className="select">
                                <div onClick={this.handleOnSelectWidgetEvent.bind(this, "-1")} className="option" data-value="-1">{this.NoEvent}</div>
                                {
                                    this.widgetEvents.map(function (widgetEvent){
                                        return (
                                            <div key={widgetEvent.value +"_"+ widgetEvent.share_way } onClick={this.handleOnSelectWidgetEvent.bind(this, widgetEvent.value, widgetEvent.share_way )} className="option" data-value={widgetEvent.value}>
                                                {widgetEvent.name}
                                            </div>
                                        )
                                    }.bind(this))
                                }
                                </div>
                            </div>
                        </div>
                        <div className="form-group select-evtype-group">
                            <label className="control-label">{$._('After editor click the widget')}</label>
                            <span>{this.typeName}</span>
                        </div>
                        <div>
                            {formModelTypeNode}
                        </div>
                        <div className="jiaohu-hidden" value={form.model.type} style={{display:"none"}}>
                        </div>
                        <div className="rowli event-type-string">
                        </div>
                        <div className="rowli">
                            {formModelTypeInnerNode}
                        </div>
                        <div className="rowli">
                            {widgetTypeNode}
                        </div>
                    </form>
                </div>
        )
    }
}

const mapStateToProps = ({ editor, widgets, timelines ,pages}) => {
  const pageId = editor.selectedPageId;
  return {
      status: editor.status,
      widgets: widgets.filter(w => w.page_id === pageId),
      timelines: timelines.filter(t => t.page_id === pageId),
      pages,
      selectedPageId: pageId
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...editorActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(WidgetEvent);
